import numpy as np
import Core.functions as functions
import matplotlib.pyplot as plt

# 开始算法
# 设置算法结束为迭代一千次
'''
参数说明:
n: 种群数量, 设置为200
cross_point: 交叉点, 设置为13(交叉后6位)
cross_rate: 交叉率, 设置为0.7
mutation_rate: 变异率, 设置为0.1
'''
n = 100
cross_point = 13
cross_rate = 0.7
mutation_rate = 0.1

# 初始种群
p = functions.init_population(n)

for i in range(10000):
    # 计算适应度
    p = functions.cal_fitness(p)
    # 编码
    p_gene = functions.encode(p)
    # 选择
    p_choice = functions.choice(p_gene)
    # 交叉
    p_cross = functions.cross(p_choice, cross_point, cross_rate)
    # 变异
    p_mutation = functions.mutation(p_cross, mutation_rate)
    # 解码
    p = functions.decode(p_mutation)
    # 记录迭代
    print('process running No.'+str(i)+'...')

# 绘图操作
fig = plt.figure()
axes = fig.add_subplot(111)  # 对于上面的fig.add_subplot(111)就是添加Axes的，参数的解释的在画板的第1行第1列的第一个位置生成一个Axes对象来准备作画
axes.set(xlim=[-1, 2], title='Genetic Algorithm',
         ylabel='Y-Axis', xlabel='X-Axis')
list_x = []
list_y = []
for i in range(len(p)):
    list_x.append(p[i].x)
for i in range(len(list_x)):
    list_y.append(functions.fitness(list_x[i]))

x = list_x
y = list_y
best_index = list_y.index(max(list_y))
best = list_x[best_index]
axes.scatter(x, y)
axes.scatter(best, max(list_y), c='r', label='best_one')
plt.show()
